#include "StdAfx.h"
#include "AudioCapture.h"

#include "MyRecordThread.h"
#include <Mmsystem.h>
#pragma comment(lib, "Winmm.lib")

CAudioCapture::CAudioCapture(void)
{
}

CAudioCapture::~CAudioCapture(void)
{
}

void waveInProc(
  HWAVEIN hwi,       
  UINT uMsg,         
  DWORD_PTR dwInstance,  
  DWORD_PTR dwParam1,    
  DWORD_PTR dwParam2     
)
{
	switch( uMsg )
	{
		case WIM_CLOSE:
			break;
		case WIM_DATA:
			break;
		case WIM_OPEN:
			{

			}

			break;
	}
}

void thread_func( void* p )
{
	MSG msg;

	while( GetMessage( &msg , NULL , 0 , 0 ) > 0 )
	{
		switch( msg.message )
		{
		case WIM_CLOSE:
			break;
		case WIM_DATA:
			break;
		case WIM_OPEN:
			{
				printf("Good");
			}
		}
	}

	printf("Exited");
}

void CAudioCapture::OpenDevice()
{
	MMRESULT result = MMSYSERR_NOERROR;

	HWAVEIN hWaveIn;

	WAVEFORMATEX waveFormat;
	waveFormat.wFormatTag = WAVE_FORMAT_PCM;
	waveFormat.nChannels = 1;
	waveFormat.nSamplesPerSec = 11025;
	waveFormat.nAvgBytesPerSec = 11025;
	waveFormat.nBlockAlign = 1;
	waveFormat.wBitsPerSample = 8;
	waveFormat.cbSize = 0;

	//result = waveInOpen( NULL , 0 ,&waveFormat , NULL , NULL , WAVE_MAPPED | WAVE_FORMAT_QUERY );

	//CWinThread* pNowThread = AfxBeginThread( CMyRecordThread::GetRuntimeClass() );
	uintptr_t tThread = _beginthread( thread_func , 0 , NULL );

	Sleep( 2000 );

	//PostThreadMessage( tThread , WIM_OPEN , 0 , 0 );

	result = waveInOpen( &hWaveIn , 0 , &waveFormat , (DWORD_PTR)tThread , 0 , CALLBACK_THREAD );
  	if( result == MMSYSERR_NOERROR  )
	{
		printf("OK");
	}

	WAVEHDR pwh;
	pwh.dwBufferLength = 1024;
	pwh.lpData = new char[1024];
	pwh.dwFlags = WHDR_BEGINLOOP | WHDR_ENDLOOP ;
	pwh.dwBufferLength = 1024;

	result = waveInPrepareHeader( hWaveIn , &pwh , sizeof( pwh ) );
	result = waveInAddBuffer( hWaveIn , &pwh , sizeof( pwh ) );

	result = waveInStart( hWaveIn );

	printf("Hello");
}
